package com.rightsidetech.http.controller.admin.system;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.PageRequest;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.http.aspect.Auth;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.mall.entity.MallCommoditySpecs;
import com.rightsidetech.mall.entity.MallCommodityWithBLOBs;
import com.rightsidetech.mall.service.MallCommodityService;
import com.rightsidetech.system.dtos.request.RuleCommoditySaveReq;
import com.rightsidetech.system.dtos.request.RuleCommoditySpecsSaveReq;
import com.rightsidetech.system.dtos.request.RuleCommodityUpReq;
import com.rightsidetech.system.dtos.request.SysRuleStatusReq;
import com.rightsidetech.system.dtos.response.SysRuleCommodityDetailResp;
import com.rightsidetech.system.dtos.response.SysRuleCommodityPageResp;
import com.rightsidetech.system.service.SysRuleCommodityIntegralService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/sys_commodity_rule")
@Api(tags = "商品积分规则相关")
@ShenyuSpringMvcClient(path = "/admin/sys_commodity_rule/**")
public class SysRuleCommodityIntegralController {

    @Resource
    private SysRuleCommodityIntegralService sysRuleCommodityIntegralService;
    @Resource
    private MallCommodityService mallCommodityService;

    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @PostMapping("/save")
    @ApiOperation("添加商品积分规则")
    public ResponseData saveRule(@RequestBody RuleCommoditySaveReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        ResponseData check = check(req);
        if(ObjectUtil.isNotEmpty(check)){
            return check;
        }
        ResponseData data = sysRuleCommodityIntegralService.save(req);
        if(data.getCodeId() == 1){
            MallCommodityWithBLOBs record = new MallCommodityWithBLOBs();
            record.setId(req.getCommodityId());
            record.setIsIntegral((byte)1);
            mallCommodityService.updateByPrimaryKeySelective(record);
        }
        return data;
    }

    private ResponseData check(RuleCommoditySaveReq req){
        MallCommodityWithBLOBs commodity = mallCommodityService.selectByPrimaryKey(req.getCommodityId());
        if(ObjectUtil.isEmpty(commodity)){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到此商品");
        }
        req.setCommodityName(commodity.getCommodityName());
        List<RuleCommoditySpecsSaveReq> list = req.getList();
        if(CollUtil.isNotEmpty(list)){
            Set<String> set = list.stream().map(RuleCommoditySpecsSaveReq::getBarCode).collect(Collectors.toSet());
            if(set.size() < list.size()){
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"商品规格条码不可重复");
            }
            for (RuleCommoditySpecsSaveReq specsSaveReq : list) {
                ConstraintViolation validate1 = BeanValidator.validate(specsSaveReq);
                if (validate1 != null) {
                    return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate1.getMessage());
                }
                MallCommoditySpecs specs = mallCommodityService.selectSpecsByCommodityAndBarCode(req.getCommodityId(),specsSaveReq.getBarCode());
                if(ObjectUtil.isEmpty(specs)){
                    return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"其中有未找到的规格商品");
                }
                specsSaveReq.setSpecs(specs.getCommoditySpecs());
                specsSaveReq.setBarCode(specs.getBarCode());
            }
        }else {
            if(StrUtil.isNotBlank(commodity.getSpecsJson())){
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此商品存在规格请选择规格后创建积分规则");
            }
            if(ObjectUtil.isEmpty(req.getRuleValue())){
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"商品没规格时，积分规则不可为空");
            }
        }
        return null;
    }

    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/page")
    @ApiOperation("分页列表")
    public ResponseData<PageInfo<SysRuleCommodityPageResp>> page(PageRequest req){
        return sysRuleCommodityIntegralService.page(req);
    }


    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/get_child")
    @ApiOperation("懒加载获取子级")
    public ResponseData<List<SysRuleCommodityPageResp>> getChild(DelReq req){
        return sysRuleCommodityIntegralService.getChild(req);
    }


    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/detail")
    @ApiOperation("积分规则详情")
    public ResponseData<SysRuleCommodityDetailResp> details(DelReq req){
        return sysRuleCommodityIntegralService.detail(req);
    }


    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @PostMapping("/update")
    @ApiOperation("修改积分规则")
    public ResponseData updateRule(@RequestBody RuleCommodityUpReq req)throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        ResponseData check = check(req);
        if(ObjectUtil.isNotEmpty(check)){
            return check;
        }
        return sysRuleCommodityIntegralService.update(req);
    }

    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @PostMapping("/up_status")
    @ApiOperation("开启关闭规则")
    public ResponseData upStatus(@RequestBody SysRuleStatusReq req){
        return sysRuleCommodityIntegralService.updateStatus(req);
    }


    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/search")
    @ApiOperation("未创建过积分商品名称下拉选")
    public ResponseData onIntegralCom(@RequestParam(required = false) String commodityName){
        return mallCommodityService.noIntegral(commodityName);
    }
}
